# -*- coding: utf-8 -*-

from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.db.models.fields.related import RelatedField
from django.forms import model_to_dict
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

import logging
import json

logger = logging.getLogger(__name__)


class JWTAuthentication(JSONWebTokenAuthentication):
    """
    自定义JWT认证方式
    """

    def authenticate(self, request):
        try:
            user_model = get_user_model()
            user: User = user_model.objects.get(pk=1)
            payload = jwt_payload_handler(user)
            jwt_value = jwt_encode_handler(payload)
            user_dict = model_to_dict(user)

            related_field = dict()
            for field in user_model._meta.get_fields():  # noqa
                if issubclass(type(field), RelatedField):
                    field_value = user_dict.pop(field.name)
                    related_field[field.name] = field_value
            user_dict['-'] = related_field
            user_json = json.dumps(user_dict, default=str)
            user_object = User(**user_dict)
            # for field_name in related_field.keys():
            #     user_object
            return user, jwt_value
        except Exception as e:
            logger.info(f'use JSONWebTokenAuthentication:{repr(e)}')
            return super().authenticate(request)

    def authenticate_credentials(self, payload):
        return super().authenticate_credentials(payload)
